<script lang="ts">
import {defineComponent, onMounted, reactive, ref, toRefs} from 'vue'
import type {LoginForm} from "@/views/login/types/loginType.ts";
import {PASSWORD_KEY, PASSWORD_REGULAR, REMEMBER_ME_KEY, USERNAME_KEY} from "@/views/login/constant/loginConstant.ts";
import {storageHook} from "@/hooks/storagehook.ts";
import {login} from "../api/loginApi.ts"
import router from "@/router/router.ts";
import {Hide, View} from "@element-plus/icons-vue";
import {sendGlobalMessage} from "@/hooks/globalmessage.ts";
import {GlobalMessage} from "@/event/eventglobalmessage.ts";
import {setTokenToCookies} from "@/common/commonJs/login.ts";


export default defineComponent({
  name: 'login-by-username',
  components: {View, Hide},

  setup: function () {

    onMounted(() => {
      data.rememberMe = hooks.sessionStorage.get(REMEMBER_ME_KEY) || false
      if (data.rememberMe) {
        data.loginForm.username = hooks.sessionStorage.get(USERNAME_KEY) || ""
        data.loginForm.password = hooks.sessionStorage.get(PASSWORD_KEY) || ""
      }

    })

    const hooks = {
      sessionStorage: storageHook().storage,
    }
    const data = reactive({
      loginForm: <LoginForm>{
        username: "admin",
        password: "ikun666",
      },
      show: false,
      rememberMe: false,
      isLogin: false
    })

    const methods = {
      showPassword() {
        data.show = !data.show
      },
      changRememberMe() {
        data.rememberMe = !data.rememberMe

        if (!data.rememberMe) {
          hooks.sessionStorage.remove(REMEMBER_ME_KEY)
        } else {
          hooks.sessionStorage.set(REMEMBER_ME_KEY, data.rememberMe.toString())
        }
      },
      forgotPassword() {

      },
      async login() {
        refs.loginFormRef.value.validate(async (validate: boolean) => {

          if (validate) {
            data.isLogin = true
            const res = await login(data.loginForm)
            data.isLogin = false
            if (data.rememberMe) {
              const sessionStorage = hooks.sessionStorage;
              sessionStorage.set(REMEMBER_ME_KEY, data.rememberMe.toString())
              sessionStorage.set(USERNAME_KEY, data.loginForm.username)
              sessionStorage.set(PASSWORD_KEY, data.loginForm.password)
            }
            //todo 设置token 和 refreshToken
            setTokenToCookies(res.data?.token, res.data?.expirationTime, res.data?.refreshToken, res.data?.refreshTime)

            await router.push("/layout")

            sendGlobalMessage(new GlobalMessage().buildMessage('好久不见:' + data.loginForm.username || res.data.username))
          }

        })

      }
    }

    const validators = {
      validatePassword(rule: any, value: string, callback: (arg0: Error | undefined) => void) {

        if (!PASSWORD_REGULAR.test(value)) {
          callback(new Error('密码必须包含字母数字,长度不小于6位'))
        } else {
          callback(undefined)
        }
      }
    }


    const rules = reactive({
      username: [{required: true, message: "请输入用户名", trigger: "blur"}],
      password: [{required: true, message: "请输入密码", trigger: "blur"},
        {
          validator: validators.validatePassword, trigger: 'blur'
        }]
    })

    const refs = {
      loginFormRef: ref()
    }


    return {
      ...toRefs(data),
      ...hooks,
      ...methods,
      validators,
      rules,
      ...refs
    }
  }
})
</script>

<template>
  <div class="bg">
    <div class="topImg">

      <el-image class="img" src="/images/login/owl-login.png"/>
      <div v-if="show" class="handImg">

        <el-image class="left"
                  src="/images/login/owl-login-arm-left.png"/>

        <el-image class="right"
                  src="/images/login/owl-login-arm-right.png"/>
      </div>

      <div v-if="!show">
        <div class="handPoint"
             style="left:40px;"></div>
        <div class="handPoint"
             style="right:40px"></div>
      </div>

    </div>


    <div class="login">
      <el-form
          ref="loginFormRef"
          style="width: 300px;"
          :model="loginForm"
          label-width="auto"
          :rules="rules"
          class="demo-ruleForm"
          :scroll-into-view-options="{alignToTop:false,scrollIntoViewOptions:{
            behavior:'smooth'
          }}"

      >

        <el-form-item
            label="账号"
            prop="username"
            :required="true"
        >
          <el-input
              v-model="loginForm.username"
              type="text"
              autocomplete="off"
              placeholder="请输入账号"
          />
        </el-form-item>

        <el-form-item
            label="密码"
            prop="password"
            :required="true"
        >
          <el-input
              v-model="loginForm.password"
              :type="show?'text':'password'"
              placeholder="请输入密码"

          >
            <template #suffix>
              <el-icon @click="showPassword" style="cursor:pointer">
                <View v-if="show"/>
                <Hide v-else/>
              </el-icon>

            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <div style="width: 100%;display: flex;flex-direction: column">
            <div>
              <el-row>

                <el-col :span="6" :offset="4">
                  <input type="checkbox" :checked="rememberMe" @change="changRememberMe"/>记住我
                </el-col>
                <el-col :span="6" :offset="4">
                  <el-button type="text" @click="forgotPassword" size="small" style="color: #9f6464">忘记密码?
                  </el-button>
                </el-col>
              </el-row>
            </div>
            <div style="width:100%;height:40px;display: flex;flex-direction: row;justify-content: center;">
              <el-button style="width: 80%;height:100%;background-color:#f8107a;border-radius: 20px"
                         @click="login"
                         type="primary"
                         :disabled="isLogin"
              >
                点击登录
              </el-button>
            </div>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<style lang="scss" scoped>


.bg {
  dispaly: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;

  .topImg {
    position: relative;
    width: 300px;
    margin-left: 5%;
    overflow: hidden;

    .img {
      margin-left: 15%;
      margin-bottom: -5%;
    }

    .handImg {
      position: absolute;
      bottom: -75%;
      perspective: 1000px;

      .left {
        left: 75px;
        transform-origin: top left;
        transition: ease-in-out 0.5s;
        animation: watchPasswordLeft 0.25s ease-in-out forwards;
      }

      .right {
        left: 150px;
        transform-origin: top right;
        transition: ease-in-out 0.5s;
        animation: watchPasswordRight 0.25s ease-in-out forwards;
      }

    }


    .handPoint {
      position: absolute;
      bottom: -10px;
      width: 30px;
      height: 20px;
      border-radius: 50%;
      background-color: #191a23
    }
  }

  .login {
    width: 100%;
    height: 100%;

  }
}


@keyframes watchPasswordRight {
  0% {
    transform: rotateX(0) rotateZ(0);
    /* 初始状态，图片向下翻转180度 */
  }

  100% {
    transform: rotateX(180deg) rotateZ(45deg);
    /* 结束状态，向上翻转并额外向右旋转45度 */
  }
}

@keyframes watchPasswordLeft {
  0% {
    transform: rotateX(0) rotateZ(0);
  }

  100% {
    transform: rotateX(180deg) rotateZ(-45deg);

    /* 结束状态，向上翻转并额外向右旋转45度 */
  }
}

</style>